<template>
  <el-table :data="tableData" table-layout='auto' stripe border="true" style="width: 100%">
    <el-table-column prop="code" label="代码" min-width='20'> </el-table-column>
    <el-table-column prop="name" label="名称" min-width='20'> </el-table-column>
    <el-table-column prop="price" label="价格" min-width='20'> </el-table-column>
    <el-table-column prop="volume" label="成交量" min-width='20'> </el-table-column>
    <el-table-column prop="qrr" label="量比" min-width='20'> </el-table-column>
    <el-table-column prop="duration" label="持续时间"> </el-table-column>
  </el-table>
</template>

<script>

import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      tableData: [
        {
          code: "000000",
          name: "XX科技",
          price: "88.88",
          volume: "9999",
          qrr: "3.0",
          duration: "66s",
        },
      ],
      connecting: false,
    };
  },
  mounted() {
    document.title = '鹰眼选股';
    this.conWebSocket();
  },
  methods: {
    clearReconnectState() {
            console.log('this.timer ' + this.timer);//我是定时执行
      if (this.timer) {
            console.log('清除重连');//我是定时执行
        clearTimeout(this.timer);
        this.timer = undefined;
      }
      this.connecting = false;
    },
    conWebSocket() {
      if (this.connecting) {
        console.log("connecting...");
        return;
      }

      let vm = this;
      if (window.WebSocket) {
        let ws_url = "ws://" + window.location.hostname + "/shares";
        console.log("server: " + ws_url);
        vm.socket = new WebSocket(ws_url);
        let socket = vm.socket;

        vm.connecting = true;

        socket.onopen = function (e) {
          console.log("连接服务器成功");
          ElMessage('连接服务器成功');

          vm.clearReconnectState();
        };
        socket.onclose = function (e) {
          console.log("连接服务器失败");
          ElMessage('连接服务器失败');

          vm.clearReconnectState();
          vm.timer = setTimeout(function () {
            console.log('重连');//我是定时执行
            vm.conWebSocket();
          }, 5000);
        };
        socket.onerror = function () {
          vm.clearReconnectState();
          console.log("onerror");
        };
        // 接收服务器的消息
        socket.onmessage = function (e) {
          let msg = JSON.parse(e.data);
          console.log("收到消息: " + msg.type);
          if (msg.type == 'handshake') {
            return;
          }

          if (msg.type == 'notity') {
            vm.tableData = msg.data;
          }

        };
      }
    },
  },
};
</script>